package com.like.lazyfragment

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.like.lazyfragment.ui2.*
import kotlinx.android.synthetic.main.activity_main2.*
import androidx.fragment.app.FragmentManager as FragmentManager1

/**
 * 懒加载实现方案1  通过setUserVisiblerHint
 */
class Main2Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        val arrayListOf = arrayListOf<Fragment>()
        arrayListOf.add(Fragment1())
        arrayListOf.add(Fragment2())
        arrayListOf.add(Fragment3())
        arrayListOf.add(Fragment4())
        arrayListOf.add(Fragment5())
        val myAdapter = MyAdapter(arrayListOf, supportFragmentManager)



        viewPager.adapter = myAdapter;
        tabLayout.setupWithViewPager(viewPager)

        viewPager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                var child: MyAdapter? = viewPager.adapter as? MyAdapter
               Log.w("--------------------->",""+child?.getItem(position).hashCode())
            }

        })
    }

    class MyAdapter(var fragments: ArrayList<Fragment>, fm: FragmentManager1) :
        FragmentPagerAdapter(fm) {
        private val arrayOf = arrayOf(
            "第一页",
            "第二页",
            "第三页",
            "第四页",
            "第五页"
        )

        override fun getItem(position: Int): Fragment {
            return fragments[position]
        }

        override fun getCount(): Int {
            return arrayOf.size;
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return arrayOf[position]
        }
    }

}
